好的,我会给你完整的代码实现。由于代码较长,我会分几个部分发送,但每个部分都是完整的文件。

第一部分 - core/src/storage_core.c的完整实现:

```c
// core/src/storage_core.c 
#include <string.h>
#include "esp_log.h"
#include "storage_interface.h"
#include "storage_device_interface.h" 
#include "storage_extension_interface.h"
#include "storage_types.h"

static const char *TAG = "storage_core";

// 核心存储接口实现
static esp_err_t core_init(storage_context_t* ctx, const void* config);
static esp_err_t core_deinit(storage_context_t* ctx);
static esp_err_t core_read(storage_context_t* ctx, const char* path, void* data, size_t size, size_t* read_size);
static esp_err_t core_write(storage_context_t* ctx, const char* path, const void* data, size_t size);
static esp_err_t core_append(storage_context_t* ctx, const char* path, const void* data, size_t size);
static esp_err_t core_remove(storage_context_t* ctx, const char* path);
static esp_err_t core_rename(storage_context_t* ctx, const char* old_path, const char* new_path);
static esp_err_t core_mkdir(storage_context_t* ctx, const char* path);
static esp_err_t core_rmdir(storage_context_t* ctx, const char* path);
static esp_err_t core_stat(storage_context_t* ctx, const char* path, void* st);
static esp_err_t core_exists(storage_context_t* ctx, const char* path, bool* exists);
static esp_err_t core_list(storage_context_t* ctx, const char* path, void* files, size_t* count);
static esp_err_t core_format(storage_context_t* ctx);
static esp_err_t core_get_info(storage_context_t* ctx, uint32_t* total, uint32_t* used);

// 存储接口实例
static const storage_interface_t g_storage_interface = {
    .init = core_init,
    .deinit = core_deinit,
    .read = core_read, 
    .write = core_write,
    .append = core_append,
    .remove = core_remove,
    .rename = core_rename,
    .mkdir = core_mkdir,
    .rmdir = core_rmdir,
    .stat = core_stat,
    .exists = core_exists,
    .list = core_list,
    .format = core_format,
    .get_info = core_get_info
};

// 获取接口实例
const storage_interface_t* storage_get_interface(void) {
    return &g_storage_interface;
}

// 核心初始化实现
static esp_err_t core_init(storage_context_t* ctx, const void* config) {
    if (!ctx || !config) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;

    // 创建互斥锁
    ctx->mutex = xSemaphoreCreateMutex();
    if (!ctx->mutex) {
        ESP_LOGE(TAG, "Failed to create mutex");
        return ESP_ERR_NO_MEM;
    }

    // 初始化子模块上下文
    memset(&ctx->modules, 0, sizeof(ctx->modules));

    do {
        // 复制配置
        memcpy(&ctx->config, config, sizeof(ctx->config));

        // 初始化错误处理模块
        ret = storage_error_init(ctx); 
        if (ret != ESP_OK) break;

        // 初始化缓存模块
        ret = storage_cache_init(ctx);
        if (ret != ESP_OK) break;

        // 初始化DMA模块
        ret = storage_dma_init(ctx);
        if (ret != ESP_OK) break;

        // 初始化保护模块  
        ret = storage_protection_init(ctx);
        if (ret != ESP_OK) break;

        ctx->mounted = true;

    } while(0);

    // 错误时清理资源
    if (ret != ESP_OK) {
        if (ctx->modules.protect_ctx) storage_protection_deinit(ctx);
        if (ctx->modules.dma_ctx) storage_dma_deinit(ctx);
        if (ctx->modules.cache_ctx) storage_cache_deinit(ctx);
        if (ctx->modules.error_ctx) storage_error_deinit(ctx);
        if (ctx->mutex) {
            vSemaphoreDelete(ctx->mutex);
            ctx->mutex = NULL;
        }
    }

    return ret;
}

// 核心注销实现
static esp_err_t core_deinit(storage_context_t* ctx) {
    if (!ctx || !ctx->mounted) {
        return ESP_ERR_INVALID_STATE;
    }

    // 按初始化顺序反向清理
    storage_protection_deinit(ctx);
    storage_dma_deinit(ctx);
    storage_cache_deinit(ctx);
    storage_error_deinit(ctx);

    if (ctx->mutex) {
        vSemaphoreDelete(ctx->mutex);
        ctx->mutex = NULL;
    }

    ctx->mounted = false;
    
    return ESP_OK;
}

// 基本读操作实现
static esp_err_t core_read(storage_context_t* ctx, const char* path, void* data, size_t size, size_t* read_size) {
    if (!ctx || !ctx->mounted || !path || !data || !read_size) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    do {
        // 尝试从缓存读取
        if (ctx->modules.cache_ctx) {
            ret = storage_cache_read(ctx, path, data, size, read_size);
            if (ret == ESP_OK) break;
        }

        // 从设备读取
        if (ctx->device && ctx->device->read) {
            ret = ctx->device->read(ctx, path, data, size, read_size);
        } else {
            ret = ESP_ERR_NOT_SUPPORTED;
        }

    } while(0);

    xSemaphoreGive(ctx->mutex);

    return ret;
}

// 基本写操作实现
static esp_err_t core_write(storage_context_t* ctx, const char* path, const void* data, size_t size) {
    if (!ctx || !ctx->mounted || !path || (!data && size > 0)) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    do {
        // 写入设备
        if (ctx->device && ctx->device->write) {
            ret = ctx->device->write(ctx, path, data, size);
            if (ret != ESP_OK) break;
        } else {
            ret = ESP_ERR_NOT_SUPPORTED;
            break;
        }

        // 更新缓存
        if (ctx->modules.cache_ctx) {
            ret = storage_cache_update(ctx, path, data, size);
        }

    } while(0);

    xSemaphoreGive(ctx->mutex);

    return ret;
}

// 文件追加实现
static esp_err_t core_append(storage_context_t* ctx, const char* path, const void* data, size_t size) {
    if (!ctx || !ctx->mounted || !path || (!data && size > 0)) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;
    size_t original_size = 0;
    uint8_t* buffer = NULL;

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    do {
        // 获取原文件大小
        struct stat st;
        if (core_stat(ctx, path, &st) == ESP_OK) {
            original_size = st.st_size;
        }

        // 分配新缓冲区
        buffer = malloc(original_size + size);
        if (!buffer) {
            ret = ESP_ERR_NO_MEM;
            break;
        }

        // 读取原文件内容
        size_t read_size;
        if (original_size > 0) {
            ret = core_read(ctx, path, buffer, original_size, &read_size);
            if (ret != ESP_OK) break;
        }

        // 追加新数据
        memcpy(buffer + original_size, data, size);

        // 写入完整文件
        ret = core_write(ctx, path, buffer, original_size + size);

    } while(0);

    if (buffer) {
        free(buffer);
    }

    xSemaphoreGive(ctx->mutex);

    return ret;
}

// 文件删除实现
static esp_err_t core_remove(storage_context_t* ctx, const char* path) {
    if (!ctx || !ctx->mounted || !path) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    do {
        // 从设备删除
        if (ctx->device && ctx->device->remove) {
            ret = ctx->device->remove(ctx, path);
            if (ret != ESP_OK) break;
        } else {
            ret = ESP_ERR_NOT_SUPPORTED;
            break;
        }

        // 从缓存移除
        if (ctx->modules.cache_ctx) {
            storage_cache_remove(ctx, path);
        }

    } while(0);

    xSemaphoreGive(ctx->mutex);

    return ret;
}

// 文件重命名实现
static esp_err_t core_rename(storage_context_t* ctx, const char* old_path, const char* new_path) {
    if (!ctx || !ctx->mounted || !old_path || !new_path) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    do {
        // 在设备上重命名
        if (ctx->device && ctx->device->rename) {
            ret = ctx->device->rename(ctx, old_path, new_path);
            if (ret != ESP_OK) break;
        } else {
            ret = ESP_ERR_NOT_SUPPORTED;
            break;
        }

        // 更新缓存
        if (ctx->modules.cache_ctx) {
            ret = storage_cache_rename(ctx, old_path, new_path);
        }

    } while(0);

    xSemaphoreGive(ctx->mutex);

    return ret;
}

// 目录创建实现
static esp_err_t core_mkdir(storage_context_t* ctx, const char* path) {
    if (!ctx || !ctx->mounted || !path) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    if (ctx->device && ctx->device->mkdir) {
        ret = ctx->device->mkdir(ctx, path);
    } else {
        ret = ESP_ERR_NOT_SUPPORTED;
    }

    xSemaphoreGive(ctx->mutex);

    return ret;
}

// 目录删除实现
static esp_err_t core_rmdir(storage_context_t* ctx, const char* path) {
    if (!ctx || !ctx->mounted || !path) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    if (ctx->device && ctx->device->rmdir) {
        ret = ctx->device->rmdir(ctx, path);
    } else {
        ret = ESP_ERR_NOT_SUPPORTED;
    }

    xSemaphoreGive(ctx->mutex);

    return ret;
}

// 文件状态获取实现
static esp_err_t core_stat(storage_context_t* ctx, const char* path, void* st) {
    if (!ctx || !ctx->mounted || !path || !st) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    if (ctx->device && ctx->device->stat) {
        ret = ctx->device->stat(ctx, path, st);
    } else {
        ret = ESP_ERR_NOT_SUPPORTED;
    }

    xSemaphoreGive(ctx->mutex);

    return ret;
}

// 文件存在检查实现
static esp_err_t core_exists(storage_context_t* ctx, const char* path, bool* exists) {
    if (!ctx || !ctx->mounted || !path || !exists) {
        return ESP_ERR_INVALID_ARG;
    }

    struct stat st;
    esp_err_t ret = core_stat(ctx, path, &st);
    
    *exists = (ret == ESP_OK);
    return ESP_OK;
}

// 目录列表获取实现
static esp_err_t core_list(storage_context_t* ctx, const char* path, void* files, size_t* count) {
    if (!ctx || !ctx->mounted || !path || !files || !count) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    if (ctx->device && ctx->device->list) {
        ret = ctx->device->list(ctx, path, files, count);
    } else {
        ret = ESP_ERR_NOT_SUPPORTED;
    }

    xSemaphoreGive(ctx->mutex);

    return ret;
}

// 格式化实现
static esp_err_t core_format(storage_context_t* ctx) {
    if (!ctx || !ctx->mounted) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    do {
        // 格式化设备
        if (ctx->device && ctx->device->format) {
            ret = ctx->device->format(ctx);
            if (ret != ESP_OK) break;
        } else {
            ret = ESP_ERR_NOT_SUPPORTED;
            break;
        }

        // 清空缓存
        if (ctx->modules.cache_ctx) {
            storage_cache_clear(ctx);
        }

    } while(0);

    xSemaphoreGive(ctx->mutex);

    return ret;
}

// 存储信息获取实现
static esp_err_t core_get_info(storage_context_t* ctx, uint32_t* total, uint32_t* used) {
    if (!ctx || !ctx->mounted || !total || !used) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    if (ctx->device && ctx->device->get_info) {
        ret = ctx->device->get_info(ctx, total, used);
    } else {
        ret = ESP_ERR_NOT_SUPPORTED;
    }

    xSemaphoreGive(ctx->mutex);

    return ret;
}

// 设备注册实现
esp_err_t storage_register_device(storage_context_t* ctx, 
                                const storage_device_interface_t* device,
                                const void* config) {
    if (!ctx || !device) {
        return ESP_ERR_INVALID_ARG;
    }

    if (ctx->device) {
        return ESP_ERR_INVALID_STATE;
    }

    // 验证必要的设备操作接口
    if (!device->init || !device->deinit || 
        !device->read || !device->write) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    do {
        // 初始化设备
        ret = device->init(config);
        if (ret != ESP_OK) {
            break;
        }

        // 存储设备接口
        ctx->device = device;

    } while(0);

    xSemaphoreGive(ctx->mutex);

    return ret;
}

// 设备解注册实现
esp_err_t storage_unregister_device(storage_context_t* ctx) {
    if (!ctx || !ctx->device) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    // 注销设备
    if (ctx->device->deinit) {
        ret = ctx->device->deinit();
    }

    ctx->device = NULL;

    xSemaphoreGive(ctx->mutex);

    return ret;
}



// core/src/storage_ops.c
#include "esp_log.h"
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include "storage.h"

static const char *TAG = "storage_ops";

esp_err_t storage_stat(storage_context_t *ctx, const char *path, struct stat *st) {
    if (!ctx || !ctx->mounted || !path || !st) {
        return ESP_ERR_INVALID_ARG;
    }

    char full_path[FILE_PATH_MAX] = {0};
    snprintf(full_path, sizeof(full_path), "%s%s", ctx->config.base_path, path);

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);
    
    int ret = stat(full_path, st);
    
    xSemaphoreGive(ctx->mutex);

    if (ret != 0) {
        ESP_LOGE(TAG, "Failed to get file stats: %s (errno: %d)", full_path, errno);
        return ESP_FAIL;
    }

    return ESP_OK;
}


esp_err_t storage_exists(storage_context_t *ctx, const char *path, bool *exists) {
    if (!ctx || !ctx->mounted || !path || !exists) {
        return ESP_ERR_INVALID_ARG;
    }

    char full_path[FILE_PATH_MAX] = {0};
    struct stat st;

    snprintf(full_path, sizeof(full_path), "%s%s", ctx->config.base_path, path);

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);
    
    int ret = stat(full_path, &st);
    
    xSemaphoreGive(ctx->mutex);

    *exists = (ret == 0);
    return ESP_OK;
}


esp_err_t storage_mkdir(storage_context_t *ctx, const char *path) {
    if (!ctx || !ctx->mounted || !path) {
        return ESP_ERR_INVALID_ARG;
    }

    char full_path[FILE_PATH_MAX] = {0};
    snprintf(full_path, sizeof(full_path), "%s%s", ctx->config.base_path, path);

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    int ret = mkdir(full_path, 0755);  // 0755是标准的目录权限

    xSemaphoreGive(ctx->mutex);

    if (ret != 0) {
        ESP_LOGE(TAG, "Failed to create directory: %s (errno: %d)", full_path, errno);
        return ESP_FAIL;
    }

    ESP_LOGI(TAG, "Successfully created directory: %s", full_path);
    return ESP_OK;
}


esp_err_t storage_rmdir(storage_context_t *ctx, const char *path) {
    if (!ctx || !ctx->mounted || !path) {
        return ESP_ERR_INVALID_ARG;
    }

    char full_path[FILE_PATH_MAX] = {0};
    snprintf(full_path, sizeof(full_path), "%s%s", ctx->config.base_path, path);

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    int ret = rmdir(full_path);

    xSemaphoreGive(ctx->mutex);

    if (ret != 0) {
        ESP_LOGE(TAG, "Failed to remove directory: %s (errno: %d)", full_path, errno);
        return ESP_FAIL;
    }

    ESP_LOGI(TAG, "Successfully removed directory: %s", full_path);
    return ESP_OK;
}


esp_err_t storage_list_directory(storage_context_t *ctx, const char *path, 
                               void *files, size_t *count) {
    if (!ctx || !ctx->mounted || !path || !files || !count || *count == 0) {
        return ESP_ERR_INVALID_ARG; 
    }

    char full_path[FILE_PATH_MAX] = {0};
    file_info_t *file_list = (file_info_t *)files;

    if (snprintf(full_path, sizeof(full_path), "%s%s", 
                ctx->config.base_path, path) >= sizeof(full_path)) {
        return ESP_ERR_INVALID_SIZE;
    }

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    DIR *dir = opendir(full_path);
    if (!dir) {
        xSemaphoreGive(ctx->mutex);
        ESP_LOGE(TAG, "Failed to open directory: %s (errno: %d)", 
                 full_path, errno);
        return ESP_FAIL;
    }

    size_t index = 0;
    const size_t max_count = *count;
    struct dirent *entry;
    struct stat st;

    while ((entry = readdir(dir)) != NULL && index < max_count) {
        // 跳过. 和..
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        char file_path[FILE_PATH_MAX];
        if (snprintf(file_path, sizeof(file_path), "%s/%s", full_path, 
                    entry->d_name) >= sizeof(file_path)) {
            continue;
        }

        if (stat(file_path, &st) == 0) {
            strncpy(file_list[index].name, entry->d_name, FILE_NAME_MAX - 1);
            file_list[index].name[FILE_NAME_MAX - 1] = '\0';
            file_list[index].size = st.st_size;
            file_list[index].is_directory = S_ISDIR(st.st_mode);
            file_list[index].modified_time = st.st_mtime;
            index++;
        }
    }

    closedir(dir);
    xSemaphoreGive(ctx->mutex);

    *count = index;
    ESP_LOGI(TAG, "Listed %zu files in %s", index, full_path);
    return ESP_OK;
}


// components/dma/storage_dma.c
#include <string.h>
#include "esp_log.h"
#include "esp_heap_caps.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "storage.h"
#include "storage_dma.h"

static const char *TAG = "storage_dma";

// DMA管理器初始化
esp_err_t storage_dma_init(storage_context_t* ctx) {
    if (!ctx) {
        return ESP_ERR_INVALID_ARG;
    }

    // 分配DMA管理器
    dma_manager_t* dma = calloc(1, sizeof(dma_manager_t));
    if (!dma) {
        return ESP_ERR_NO_MEM;
    }

    // 创建缓冲区切换互斥锁
    dma->buffer_switch_mutex = xSemaphoreCreateMutex();
    if (!dma->buffer_switch_mutex) {
        free(dma);
        return ESP_ERR_NO_MEM;
    }

    // 初始化DMA缓冲区
    for (int i = 0; i < NUM_DMA_BUFFERS; i++) {
        dma->buffers[i].buffer = heap_caps_malloc(DMA_BUFFER_SIZE, 
                                                MALLOC_CAP_DMA);
        if (!dma->buffers[i].buffer) {
            storage_dma_deinit(ctx);
            return ESP_ERR_NO_MEM;
        }
        
        dma->buffers[i].size = DMA_BUFFER_SIZE;
        dma->buffers[i].in_use = false;
        
        dma->buffers[i].mutex = xSemaphoreCreateMutex();
        if (!dma->buffers[i].mutex) {
            storage_dma_deinit(ctx);
            return ESP_ERR_NO_MEM;
        }
    }

    dma->current_write_buffer = 0;
    dma->current_read_buffer = 0;
    dma->optimization_ctx = NULL;

    // 初始化DMA配置
    dma->config.optimize_transfer = true;
    dma->config.timeout = pdMS_TO_TICKS(1000);
    dma->config.max_transfer_size = DMA_BUFFER_SIZE * NUM_DMA_BUFFERS;
    dma->config.priority = 5;

    ctx->modules.dma_ctx = dma;
    
    ESP_LOGI(TAG, "DMA initialized: buffers=%d, size=%d",
             NUM_DMA_BUFFERS, DMA_BUFFER_SIZE);
             
    return ESP_OK;
}

// DMA管理器清理
void storage_dma_deinit(storage_context_t* ctx) {
    if (!ctx || !ctx->modules.dma_ctx) {
        return;
    }

    dma_manager_t* dma = (dma_manager_t*)ctx->modules.dma_ctx;

    // 清理DMA缓冲区
    for (int i = 0; i < NUM_DMA_BUFFERS; i++) {
        if (dma->buffers[i].buffer) {
            heap_caps_free(dma->buffers[i].buffer);
        }
        if (dma->buffers[i].mutex) {
            vSemaphoreDelete(dma->buffers[i].mutex);
        }
    }

    // 清理互斥锁
    if (dma->buffer_switch_mutex) {
        vSemaphoreDelete(dma->buffer_switch_mutex);
    }

    // 清理优化上下文
    if (dma->optimization_ctx) {
        free(dma->optimization_ctx);
    }

    free(dma);
    ctx->modules.dma_ctx = NULL;

    ESP_LOGI(TAG, "DMA deinitialized");
}

// DMA写入实现
esp_err_t storage_dma_write(storage_context_t* ctx, const char* path,
                           dma_data_callback_t data_cb, void* user_data) {
    if (!ctx || !ctx->modules.dma_ctx || !path || !data_cb) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;
    dma_manager_t* dma = (dma_manager_t*)ctx->modules.dma_ctx;
    bool continue_writing = true;

    while (continue_writing) {
        // 获取当前写入缓冲区
        xSemaphoreTake(dma->buffer_switch_mutex, portMAX_DELAY);
        dma_buffer_t* current_buffer = &dma->buffers[dma->current_write_buffer];
        xSemaphoreGive(dma->buffer_switch_mutex);
        
        if (xSemaphoreTake(current_buffer->mutex, portMAX_DELAY) != pdTRUE) {
            ret = ESP_ERR_TIMEOUT;
            break;
        }

        // 从回调获取数据
        size_t data_size = data_cb(current_buffer->buffer, 
                                 current_buffer->size, user_data);
        if (data_size == 0) {
            xSemaphoreGive(current_buffer->mutex);
            continue_writing = false;
            continue;
        }

        // 验证DMA传输完成
        if (dma->optimization_ctx) {
            ret = storage_dma_wait_complete(ctx, dma->config.timeout);
            if (ret != ESP_OK) {
                xSemaphoreGive(current_buffer->mutex);
                break;
            }
        }

        // 写入数据
        ret = ctx->interface->write(ctx, path, current_buffer->buffer, data_size);
        xSemaphoreGive(current_buffer->mutex);

        if (ret != ESP_OK) {
            break;
        }

        // 切换到下一个缓冲区
        xSemaphoreTake(dma->buffer_switch_mutex, portMAX_DELAY);
        dma->current_write_buffer = (dma->current_write_buffer + 1) % NUM_DMA_BUFFERS;
        xSemaphoreGive(dma->buffer_switch_mutex);
    }

    return ret;
}

// DMA读取实现
esp_err_t storage_dma_read(storage_context_t* ctx, const char* path,
                          dma_process_callback_t process_cb, void* user_data) {
    if (!ctx || !ctx->modules.dma_ctx || !path || !process_cb) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;
    dma_manager_t* dma = (dma_manager_t*)ctx->modules.dma_ctx;
    bool continue_reading = true;
    size_t read_size;

    while (continue_reading) {
        // 获取当前读取缓冲区
        xSemaphoreTake(dma->buffer_switch_mutex, portMAX_DELAY);
        dma_buffer_t* current_buffer = &dma->buffers[dma->current_read_buffer];
        xSemaphoreGive(dma->buffer_switch_mutex);
        
        if (xSemaphoreTake(current_buffer->mutex, portMAX_DELAY) != pdTRUE) {
            ret = ESP_ERR_TIMEOUT;
            break;
        }

        // 读取数据
        ret = ctx->interface->read(ctx, path, current_buffer->buffer,
                                 current_buffer->size, &read_size);
        if (ret != ESP_OK || read_size == 0) {
            xSemaphoreGive(current_buffer->mutex);
            break;
        }

        // 验证DMA传输完成
        if (dma->optimization_ctx) {
            ret = storage_dma_wait_complete(ctx, dma->config.timeout);
            if (ret != ESP_OK) {
                xSemaphoreGive(current_buffer->mutex);
                break;
            }
        }

        // 处理数据
        bool should_continue = process_cb(current_buffer->buffer, 
                                        read_size, user_data);
        xSemaphoreGive(current_buffer->mutex);

        if (!should_continue) {
            break;
        }

        // 切换到下一个缓冲区
        xSemaphoreTake(dma->buffer_switch_mutex, portMAX_DELAY);
        dma->current_read_buffer = (dma->current_read_buffer + 1) % NUM_DMA_BUFFERS;
        xSemaphoreGive(dma->buffer_switch_mutex);
    }

    return ret;
}

// DMA优化配置
esp_err_t storage_dma_optimize(storage_context_t* ctx, 
                             dma_transfer_mode_t mode) {
    if (!ctx || !ctx->modules.dma_ctx) {
        return ESP_ERR_INVALID_ARG;
    }

    dma_manager_t* dma = (dma_manager_t*)ctx->modules.dma_ctx;

    // 释放旧的优化上下文
    if (dma->optimization_ctx) {
        free(dma->optimization_ctx);
        dma->optimization_ctx = NULL;
    }

    // 创建新的优化上下文
    dma_opt_context_t* opt_ctx = calloc(1, sizeof(dma_opt_context_t));
    if (!opt_ctx) {
        return ESP_ERR_NO_MEM;
    }

    // 配置优化参数
    opt_ctx->mode = mode;
    opt_ctx->transfer_active = false;
    opt_ctx->events = xEventGroupCreate();
    if (!opt_ctx->events) {
        free(opt_ctx);
        return ESP_ERR_NO_MEM;
    }

    dma->optimization_ctx = opt_ctx;

    return ESP_OK;
}


// DMA 传输等待完成
esp_err_t storage_dma_wait_complete(storage_context_t* ctx, TickType_t timeout) {
    if (!ctx || !ctx->modules.dma_ctx) {
        return ESP_ERR_INVALID_ARG;
    }

    dma_manager_t* dma = (dma_manager_t*)ctx->modules.dma_ctx;
    dma_opt_context_t* opt_ctx = dma->optimization_ctx;

    if (!opt_ctx || !opt_ctx->transfer_active) {
        return ESP_ERR_INVALID_STATE;
    }

    EventBits_t bits = xEventGroupWaitBits(opt_ctx->events,
                                          DMA_TRANSFER_COMPLETE_BIT,
                                          pdTRUE,
                                          pdTRUE,
                                          timeout);

    if ((bits & DMA_TRANSFER_COMPLETE_BIT) == 0) {
        return ESP_ERR_TIMEOUT;
    }

    opt_ctx->transfer_active = false;
    return ESP_OK;
}

// 获取DMA传输状态
esp_err_t storage_dma_get_status(storage_context_t* ctx, 
                                size_t* transferred_size) {
    if (!ctx || !ctx->modules.dma_ctx || !transferred_size) {
        return ESP_ERR_INVALID_ARG;
    }

    dma_manager_t* dma = (dma_manager_t*)ctx->modules.dma_ctx;
    dma_opt_context_t* opt_ctx = dma->optimization_ctx;

    if (!opt_ctx) {
        return ESP_ERR_INVALID_STATE;
    }

    *transferred_size = opt_ctx->transferred_size;
    return ESP_OK;
}

#include <string.h>
#include "esp_log.h"
#include "esp_heap_caps.h"
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "storage.h"

static const char *TAG = "storage_dma_opt";

#define DMA_TRANSFER_COMPLETE_BIT (1 << 0)

// DMA传输优化配置结构
typedef struct {
    dma_transfer_mode_t mode;
    dma_descriptor_t *desc_chain;
    size_t desc_count;
    EventGroupHandle_t events;
    bool transfer_active;
} dma_opt_context_t;


// DMA优化上下文初始化
static dma_opt_context_t* dma_opt_init(file_system_t *fs) {
    if (!fs->dma_mgr) {
        return NULL;
    }

    dma_opt_context_t *ctx = calloc(1, sizeof(dma_opt_context_t));
    if (!ctx) {
        return NULL;
    }

    ctx->events = xEventGroupCreate();
    if (!ctx->events) {
        free(ctx);
        return NULL;
    }

    return ctx;
}


// 优化DMA传输设置
esp_err_t dma_optimize_transfer(file_system_t *fs, dma_transfer_mode_t mode) {
    if (!fs || !fs->dma_mgr) {
        return ESP_ERR_INVALID_ARG;
    }

    // 释放旧的optimization context
    if (fs->dma_mgr->optimization_ctx) {
        dma_opt_context_t *old_ctx = fs->dma_mgr->optimization_ctx;
        if (old_ctx->desc_chain) {
            free(old_ctx->desc_chain);
        }
        if (old_ctx->events) {
            vEventGroupDelete(old_ctx->events);
        }
        free(old_ctx);
    }

    dma_opt_context_t *ctx = dma_opt_init(fs);
    if (!ctx) {
        return ESP_ERR_NO_MEM;
    }

    ctx->mode = mode;
    
    // 根据传输模式优化DMA设置
    switch (mode) {
        case DMA_MODE_SINGLE:
            // 配置单次传输优化参数
            for (int i = 0; i < NUM_DMA_BUFFERS; i++) {
                uint8_t *old_buf = fs->dma_mgr->buffers[i].buffer;
                if (fs->dma_mgr->buffers[i].size != DMA_OPTIMAL_BLOCK_SIZE) {
                    uint8_t *new_buf = heap_caps_realloc(NULL,
                                                     DMA_OPTIMAL_BLOCK_SIZE,
                                                     MALLOC_CAP_DMA);
                    if (!new_buf) {
                        free(ctx);
                        return ESP_ERR_NO_MEM;
                    }
                    heap_caps_free(old_buf);
                    fs->dma_mgr->buffers[i].buffer = new_buf;
                    fs->dma_mgr->buffers[i].size = DMA_OPTIMAL_BLOCK_SIZE;
                }
            }
            break;

        case DMA_MODE_SCATTER:
        case DMA_MODE_GATHER: {
            size_t optimal_size = DMA_OPTIMAL_BLOCK_SIZE / DMA_MAX_SCATTER_GATHER;
            // 配置分散/聚集传输的缓冲区
            for (int i = 0; i < NUM_DMA_BUFFERS; i++) {
                uint8_t *old_buf = fs->dma_mgr->buffers[i].buffer;
                uint8_t *new_buf = heap_caps_realloc(NULL,
                                                 optimal_size,
                                                 MALLOC_CAP_DMA);
                if (!new_buf) {
                    free(ctx);
                    return ESP_ERR_NO_MEM;
                }
                heap_caps_free(old_buf);
                fs->dma_mgr->buffers[i].buffer = new_buf;
                fs->dma_mgr->buffers[i].size = optimal_size;
            }
            break;
        }

        case DMA_MODE_CIRCULAR:
            // 配置循环传输模式
            for (int i = 0; i < NUM_DMA_BUFFERS; i++) {
                uint8_t *old_buf = fs->dma_mgr->buffers[i].buffer;
                uint8_t *new_buf = heap_caps_realloc(NULL,
                                                 DMA_PREFETCH_SIZE,
                                                 MALLOC_CAP_DMA);
                if (!new_buf) {
                    free(ctx);
                    return ESP_ERR_NO_MEM;
                }
                heap_caps_free(old_buf);
                fs->dma_mgr->buffers[i].buffer = new_buf;
                fs->dma_mgr->buffers[i].size = DMA_PREFETCH_SIZE;
            }
            break;

        default:
            free(ctx);
            return ESP_ERR_INVALID_ARG;
    }

    // 存储优化上下文
    fs->dma_mgr->optimization_ctx = ctx;
    return ESP_OK;
}


// 设置DMA描述符链
esp_err_t dma_set_descriptor_chain(file_system_t *fs, dma_descriptor_t *desc, size_t count) {
    if (!fs || !fs->dma_mgr || !desc || count == 0) {
        return ESP_ERR_INVALID_ARG;
    }

    dma_opt_context_t *ctx = fs->dma_mgr->optimization_ctx;
    if (!ctx) {
        return ESP_ERR_INVALID_STATE;
    }

    // 验证描述符链
    size_t total_size = 0;
    for (size_t i = 0; i < count; i++) {
        if (!desc[i].buf || desc[i].size == 0) {
            return ESP_ERR_INVALID_ARG;
        }
        total_size += desc[i].size;
    }

    // 检查是否超过最大传输限制
    if (total_size > DMA_PREFETCH_SIZE * NUM_DMA_BUFFERS) {
        return ESP_ERR_INVALID_SIZE;
    }

    // 保存描述符链信息
    ctx->desc_chain = malloc(count * sizeof(dma_descriptor_t));
    if (!ctx->desc_chain) {
        return ESP_ERR_NO_MEM;
    }
    memcpy(ctx->desc_chain, desc, count * sizeof(dma_descriptor_t));
    ctx->desc_count = count;

    return ESP_OK;
}


// 启动DMA传输
esp_err_t dma_start_transfer(file_system_t *fs) {
    if (!fs || !fs->dma_mgr) {
        return ESP_ERR_INVALID_ARG;
    }

    dma_opt_context_t *ctx = fs->dma_mgr->optimization_ctx;
    if (!ctx || ctx->transfer_active || !ctx->desc_chain) {
        return ESP_ERR_INVALID_STATE;
    }

    esp_err_t ret = ESP_OK;

    // 清除传输完成标志
    xEventGroupClearBits(ctx->events, DMA_TRANSFER_COMPLETE_BIT);
    
    // 获取存储设备DMA配置
    storage_dev_dma_config_t *dma_config = &fs->config.storage_dev->dma_config;

    // 根据传输模式启动相应的传输过程
    switch (ctx->mode) {
        case DMA_MODE_SINGLE:
            ret = dma_config->start_single_transfer(ctx->desc_chain);
            break;
            
        case DMA_MODE_SCATTER:
            ret = dma_config->start_scatter_transfer(ctx->desc_chain, ctx->desc_count);
            break;
            
        case DMA_MODE_GATHER:
            ret = dma_config->start_gather_transfer(ctx->desc_chain, ctx->desc_count);
            break;
            
        case DMA_MODE_CIRCULAR:
            ret = dma_config->start_circular_transfer(ctx->desc_chain, ctx->desc_count);
            break;
            
        default:
            ret = ESP_ERR_INVALID_ARG;
            break;
    }

    if (ret == ESP_OK) {
        ctx->transfer_active = true;
    }

    return ret;
}


// 等待DMA传输完成
esp_err_t dma_wait_complete(file_system_t *fs, TickType_t timeout) {
    if (!fs || !fs->dma_mgr) {
        return ESP_ERR_INVALID_ARG;
    }

    dma_opt_context_t *ctx = fs->dma_mgr->optimization_ctx;
    if (!ctx || !ctx->transfer_active) {
        return ESP_ERR_INVALID_STATE;
    }

    // 等待传输完成事件
    EventBits_t bits = xEventGroupWaitBits(ctx->events,
                                          DMA_TRANSFER_COMPLETE_BIT,
                                          pdTRUE,
                                          pdTRUE,
                                          timeout);

    if ((bits & DMA_TRANSFER_COMPLETE_BIT) == 0) {
        return ESP_ERR_TIMEOUT;
    }

    ctx->transfer_active = false;
    return ESP_OK;
}


// components/cache/storage_cache.c
#include <string.h>
#include "esp_log.h"
#include "storage.h"
#include "storage_cache.h"
#include "storage_types.h"

static const char *TAG = "storage_cache";

// 缓存初始化
esp_err_t storage_cache_init(storage_context_t* ctx) {
    if (!ctx) {
        return ESP_ERR_INVALID_ARG;
    }

    // 分配缓存管理器
    fs_cache_t* cache = calloc(1, sizeof(fs_cache_t));
    if (!cache) {
        return ESP_ERR_NO_MEM;
    }

    // 分配缓存条目数组
    cache->entries = calloc(MAX_CACHE_ENTRIES, sizeof(fs_cache_entry_t));
    if (!cache->entries) {
        free(cache);
        return ESP_ERR_NO_MEM;
    }

    // 初始化缓存配置
    cache->capacity = MAX_CACHE_ENTRIES;
    cache->max_cache_size = MAX_CACHE_SIZE;
    cache->count = 0;
    memset(&cache->stats, 0, sizeof(cache->stats));
    cache->prefetch_enabled = false;

    ctx->modules.cache_ctx = cache;
    
    ESP_LOGI(TAG, "Cache initialized: entries=%d, size=%d", 
             cache->capacity, cache->max_cache_size);
             
    return ESP_OK;
}

// 缓存清理
void storage_cache_deinit(storage_context_t* ctx) {
    if (!ctx || !ctx->modules.cache_ctx) {
        return;
    }

    fs_cache_t* cache = (fs_cache_t*)ctx->modules.cache_ctx;

    // 清理所有缓存条目
    for (size_t i = 0; i < cache->count; i++) {
        fs_cache_entry_t* entry = &cache->entries[i];
        if (entry->data) {
            free(entry->data);
        }
        if (entry->path) {
            free(entry->path);
        }
    }

    // 释放缓存资源
    free(cache->entries);
    free(cache);
    ctx->modules.cache_ctx = NULL;

    ESP_LOGI(TAG, "Cache deinitialized");
}

// 查找缓存条目
fs_cache_entry_t* storage_cache_find(storage_context_t* ctx, const char* path) {
    if (!ctx || !ctx->modules.cache_ctx || !path) {
        return NULL;
    }

    fs_cache_t* cache = (fs_cache_t*)ctx->modules.cache_ctx;

    for (size_t i = 0; i < cache->count; i++) {
        if (strcmp(cache->entries[i].path, path) == 0) {
            // 更新访问统计
            cache->entries[i].last_access = time(NULL);
            cache->entries[i].access_count++;
            cache->stats.cache_hits++;
            return &cache->entries[i];
        }
    }

    cache->stats.cache_misses++;
    return NULL;
}

// 添加缓存条目
esp_err_t storage_cache_add(storage_context_t* ctx, const char* path,
                           const void* data, size_t size) {
    if (!ctx || !ctx->modules.cache_ctx || !path || 
        (!data && size > 0)) {
        return ESP_ERR_INVALID_ARG;
    }

    fs_cache_t* cache = (fs_cache_t*)ctx->modules.cache_ctx;

    // 检查容量限制
    while (cache->count >= cache->capacity || 
           size > cache->max_cache_size) {
        storage_cache_evict(ctx);
    }

    // 分配新缓存条目
    fs_cache_entry_t* entry = &cache->entries[cache->count];
    entry->path = strdup(path);
    if (!entry->path) {
        return ESP_ERR_NO_MEM;
    }

    entry->data = malloc(size);
    if (!entry->data) {
        free(entry->path);
        return ESP_ERR_NO_MEM;
    }

    // 初始化缓存条目
    memcpy(entry->data, data, size);
    entry->size = size;
    entry->capacity = size;
    entry->dirty = false;
    entry->last_access = time(NULL);
    entry->access_count = 1;
    entry->is_prefetch = false;

    cache->count++;

    ESP_LOGD(TAG, "Added cache entry: path=%s, size=%d", path, size);

    return ESP_OK;
}

// 更新缓存条目
esp_err_t storage_cache_update(storage_context_t* ctx, const char* path,
                             const void* data, size_t size) {
    if (!ctx || !ctx->modules.cache_ctx || !path || 
        (!data && size > 0)) {
        return ESP_ERR_INVALID_ARG;
    }

    fs_cache_entry_t* entry = storage_cache_find(ctx, path);
    if (!entry) {
        return storage_cache_add(ctx, path, data, size);
    }

    // 需要重新分配缓存空间
    if (size > entry->capacity) {
        void* new_data = realloc(entry->data, size);
        if (!new_data) {
            return ESP_ERR_NO_MEM;
        }
        entry->data = new_data;
        entry->capacity = size;
    }

    // 更新缓存数据
    memcpy(entry->data, data, size);
    entry->size = size;
    entry->dirty = true;
    entry->last_access = time(NULL);
    entry->access_count++;

    return ESP_OK;
}

// 删除缓存条目
void storage_cache_remove(storage_context_t* ctx, const char* path) {
    if (!ctx || !ctx->modules.cache_ctx || !path) {
        return;
    }

    fs_cache_t* cache = (fs_cache_t*)ctx->modules.cache_ctx;

    for (size_t i = 0; i < cache->count; i++) {
        if (strcmp(cache->entries[i].path, path) == 0) {
            // 释放条目资源
            free(cache->entries[i].data);
            free(cache->entries[i].path);

            // 移动后续条目
            if (i < cache->count - 1) {
                memmove(&cache->entries[i], &cache->entries[i + 1],
                        (cache->count - i - 1) * sizeof(fs_cache_entry_t));
            }

            cache->count--;
            break;
        }
    }
}

// 淘汰缓存条目
void storage_cache_evict(storage_context_t* ctx) {
    if (!ctx || !ctx->modules.cache_ctx || 
        !((fs_cache_t*)ctx->modules.cache_ctx)->count) {
        return;
    }

    fs_cache_t* cache = (fs_cache_t*)ctx->modules.cache_ctx;

    // 查找最久未访问的条目
    size_t victim_idx = 0;
    time_t oldest_time = cache->entries[0].last_access;

    for (size_t i = 1; i < cache->count; i++) {
        if (cache->entries[i].last_access < oldest_time) {
            victim_idx = i;
            oldest_time = cache->entries[i].last_access;
        }
    }

    // 如果是脏数据，需要回写
    if (cache->entries[victim_idx].dirty) {
        // 实现回写逻辑
        cache->stats.buffer_flushes++;
    }

    // 释放条目资源
    free(cache->entries[victim_idx].data);
    free(cache->entries[victim_idx].path);

    // 移动后续条目
    if (victim_idx < cache->count - 1) {
        memmove(&cache->entries[victim_idx], 
                &cache->entries[victim_idx + 1],
                (cache->count - victim_idx - 1) * sizeof(fs_cache_entry_t));
    }

    cache->count--;
}

// 清空缓存
void storage_cache_clear(storage_context_t* ctx) {
    if (!ctx || !ctx->modules.cache_ctx) {
        return;
    }

    fs_cache_t* cache = (fs_cache_t*)ctx->modules.cache_ctx;

    for (size_t i = 0; i < cache->count; i++) {
        free(cache->entries[i].data);
        free(cache->entries[i].path);
    }

    cache->count = 0;
    memset(&cache->stats, 0, sizeof(cache->stats));
}

// 设置缓存策略
esp_err_t storage_cache_set_policy(storage_context_t* ctx, 
                                 cache_policy_t policy) {
    if (!ctx || !ctx->modules.cache_ctx) {
        return ESP_ERR_INVALID_ARG;
    }

    // TODO: 实现不同的缓存策略

    return ESP_OK;
}

// 获取缓存统计信息
esp_err_t storage_cache_get_stats(storage_context_t* ctx, void* stats) {
    if (!ctx || !ctx->modules.cache_ctx || !stats) {
        return ESP_ERR_INVALID_ARG;
    }

    fs_cache_t* cache = (fs_cache_t*)ctx->modules.cache_ctx;
    memcpy(stats, &cache->stats, sizeof(cache->stats));

    return ESP_OK;
}


// components/protection/storage_protection.c
#include <string.h>
#include "esp_log.h"
#include "esp_crc.h"
#include "storage_protection.h"
#include "storage_types.h"

static const char *TAG = "storage_protection";

// 数据保护初始化
esp_err_t storage_protection_init(storage_context_t* ctx) {
    if (!ctx) {
        return ESP_ERR_INVALID_ARG;
    }

    // 分配保护上下文
    fs_protection_t *protection = calloc(1, sizeof(fs_protection_t));
    if (!protection) {
        return ESP_ERR_NO_MEM;
    }

    // 创建互斥锁
    protection->mutex = xSemaphoreCreateMutex();
    if (!protection->mutex) {
        free(protection);
        return ESP_ERR_NO_MEM;
    }

    // 分配元数据内存
    protection->metadata = calloc(1, sizeof(protection_metadata_t));
    if (!protection->metadata) {
        vSemaphoreDelete(protection->mutex);
        free(protection);
        return ESP_ERR_NO_MEM;
    }

    // 初始化journal路径
    snprintf(protection->journal_path, sizeof(protection->journal_path),
             "%s/.journal", ctx->config.base_path);

    // 配置保护参数
    protection->config.enabled = true;
    protection->config.auto_recover = true;
    protection->config.journal_size = JOURNAL_BLOCK_SIZE;
    protection->config.sync_interval = 1000; // 1秒

    ctx->modules.protect_ctx = protection;
    
    ESP_LOGI(TAG, "Protection initialized");
    return ESP_OK;
}

// 数据保护清理
void storage_protection_deinit(storage_context_t* ctx) {
    if (!ctx || !ctx->modules.protect_ctx) {
        return;
    }

    fs_protection_t* protection = (fs_protection_t*)ctx->modules.protect_ctx;

    if (protection->mutex) {
        vSemaphoreDelete(protection->mutex);
    }

    if (protection->metadata) {
        free(protection->metadata);
    }

    free(protection);
    ctx->modules.protect_ctx = NULL;

    ESP_LOGI(TAG, "Protection deinitialized");
}

// CRC32计算
static esp_err_t calc_crc32(const void* data, size_t size, uint32_t* crc) {
    if (!data || !crc || size == 0) {
        return ESP_ERR_INVALID_ARG;
    }

    *crc = esp_crc32_be(CRC32_INITIAL_VALUE, data, size);
    return ESP_OK;
}

// 受保护的写操作
esp_err_t storage_protection_write(storage_context_t* ctx, const char* path,
                                 const void* data, size_t size) {
    if (!ctx || !ctx->modules.protect_ctx || !path || 
        (!data && size > 0)) {
        return ESP_ERR_INVALID_ARG;
    }

    fs_protection_t* protection = (fs_protection_t*)ctx->modules.protect_ctx;
    esp_err_t ret = ESP_OK;

    xSemaphoreTake(protection->mutex, portMAX_DELAY);

    do {
        // 准备元数据
        protection->metadata->magic = PROTECTION_MAGIC_NUMBER;
        protection->metadata->sequence++;
        protection->metadata->data_size = size;
        protection->metadata->timestamp = time(NULL);

        // 计算校验和
        ret = calc_crc32(data, size, &protection->metadata->crc32);
        if (ret != ESP_OK) break;

        // 写入journal
        FILE* journal = fopen(protection->journal_path, "wb");
        if (!journal) {
            ret = ESP_FAIL;
            break;
        }

        // 写入元数据
        if (fwrite(protection->metadata, sizeof(protection_metadata_t), 
                  1, journal) != 1) {
            fclose(journal);
            ret = ESP_FAIL;
            break;
        }

        // 写入数据
        if (fwrite(data, 1, size, journal) != size) {
            fclose(journal);
            ret = ESP_FAIL;
            break;
        }

        fclose(journal);

        // 写入实际文件
        ret = ctx->interface->write(ctx, path, data, size);

    } while(0);

    xSemaphoreGive(protection->mutex);
    return ret;
}

// 受保护的读操作
esp_err_t storage_protection_read(storage_context_t* ctx, const char* path,
                                void* data, size_t size, size_t* read_size) {
    if (!ctx || !ctx->modules.protect_ctx || !path || 
        !data || !read_size) {
        return ESP_ERR_INVALID_ARG;
    }

    fs_protection_t* protection = (fs_protection_t*)ctx->modules.protect_ctx;
    esp_err_t ret = ESP_OK;

    xSemaphoreTake(protection->mutex, portMAX_DELAY);

    do {
        // 读取文件
        ret = ctx->interface->read(ctx, path, data, size, read_size);
        if (ret != ESP_OK) break;

        // 验证CRC
        uint32_t calculated_crc;
        ret = calc_crc32(data, *read_size, &calculated_crc);
        if (ret != ESP_OK) break;

        // 检查journal
        FILE* journal = fopen(protection->journal_path, "rb");
        if (journal) {
            protection_metadata_t journal_metadata;
            
            // 读取journal元数据
            if (fread(&journal_metadata, sizeof(protection_metadata_t),
                     1, journal) == 1) {
                if (journal_metadata.magic == PROTECTION_MAGIC_NUMBER &&
                    journal_metadata.crc32 != calculated_crc) {
                    // CRC不匹配，从journal恢复
                    void* journal_data = malloc(journal_metadata.data_size);
                    if (journal_data) {
                        if (fread(journal_data, 1, journal_metadata.data_size,
                                journal) == journal_metadata.data_size) {
                            // 验证journal数据
                            uint32_t journal_crc;
                            if (calc_crc32(journal_data, 
                                         journal_metadata.data_size,
                                         &journal_crc) == ESP_OK &&
                                journal_crc == journal_metadata.crc32) {
                                // 恢复数据
                                size_t copy_size = 
                                    (journal_metadata.data_size < size) ?
                                    journal_metadata.data_size : size;
                                memcpy(data, journal_data, copy_size);
                                *read_size = copy_size;
                            }
                        }
                        free(journal_data);
                    }
                }
            }
            fclose(journal);
        }

    } while(0);

    xSemaphoreGive(protection->mutex);
    return ret;
}

// 一致性检查
esp_err_t storage_protection_check(storage_context_t* ctx) {
    if (!ctx || !ctx->modules.protect_ctx) {
        return ESP_ERR_INVALID_ARG;
    }

    fs_protection_t* protection = (fs_protection_t*)ctx->modules.protect_ctx;
    esp_err_t ret = ESP_OK;

    xSemaphoreTake(protection->mutex, portMAX_DELAY);

    do {
        // 检查journal文件
        FILE* journal = fopen(protection->journal_path, "rb");
        if (!journal) {
            break;  // 无journal文件，认为是一致的
        }

        protection_metadata_t journal_metadata;
        if (fread(&journal_metadata, sizeof(protection_metadata_t), 
                  1, journal) != 1) {
            ret = ESP_FAIL;
            fclose(journal);
            break;
        }

        // 检查magic number
        if (journal_metadata.magic != PROTECTION_MAGIC_NUMBER) {
            ret = ESP_FAIL;
            fclose(journal);
            break;
        }

        fclose(journal);
        
    } while(0);

    xSemaphoreGive(protection->mutex);
    return ret;
}

// 一致性恢复
esp_err_t storage_protection_recover(storage_context_t* ctx) {
    if (!ctx || !ctx->modules.protect_ctx) {
        return ESP_ERR_INVALID_ARG;
    }

    fs_protection_t* protection = (fs_protection_t*)ctx->modules.protect_ctx;
    esp_err_t ret = ESP_OK;

    xSemaphoreTake(protection->mutex, portMAX_DELAY);

    do {
        FILE* journal = fopen(protection->journal_path, "rb");
        if (!journal) {
            break;
        }

        protection_metadata_t journal_metadata;
        if (fread(&journal_metadata, sizeof(protection_metadata_t),
                  1, journal) != 1) {
            ret = ESP_FAIL;
            fclose(journal);
            break;
        }

        // 验证journal
        if (journal_metadata.magic != PROTECTION_MAGIC_NUMBER) {
            ret = ESP_FAIL;
            fclose(journal);
            break;
        }

        // 读取journal数据
        void* journal_data = malloc(journal_metadata.data_size);
        if (!journal_data) {
            ret = ESP_ERR_NO_MEM;
            fclose(journal);
            break;
        }

        if (fread(journal_data, 1, journal_metadata.data_size,
                  journal) == journal_metadata.data_size) {
            // 验证数据CRC
            uint32_t crc;
            if (calc_crc32(journal_data, journal_metadata.data_size, 
                          &crc) == ESP_OK &&
                crc == journal_metadata.crc32) {
                // TODO: 实现具体的恢复逻辑
            }
        }

        free(journal_data);
        fclose(journal);

    } while(0);

    xSemaphoreGive(protection->mutex);
    return ret;
}


// components/protection/storage_power_protection.c
#include <string.h>
#include "esp_log.h"
#include "storage_power_protection.h"
#include "storage_types.h"

static const char *TAG = "storage_power";

// 写入事务日志
static esp_err_t write_transaction_log(storage_context_t* ctx, const char* path,
                                     const void* data, size_t size) {
    char log_path[FILE_PATH_MAX];
    snprintf(log_path, sizeof(log_path), "%s%s", 
             ctx->config.base_path, TRANSACTION_PATH);
    
    FILE* f = fopen(log_path, "wb");
    if (!f) {
        ESP_LOGE(TAG, "Failed to open transaction log");
        return ESP_FAIL;
    }

    transaction_header_t header = {
        .magic = TRANSACTION_MAGIC,
        .sequence = ctx->modules.transaction->header.sequence + 1,
        .status = TRANSACTION_STARTED,
        .data_size = size
    };
    
    // 计算数据校验和
    esp_err_t ret = storage_calc_crc32(data, size, &header.checksum);
    if (ret != ESP_OK) {
        fclose(f);
        return ret;
    }

    strncpy(header.path, path, sizeof(header.path) - 1);
    header.path[sizeof(header.path) - 1] = '\0';
    
    // 写入头部
    if (fwrite(&header, sizeof(header), 1, f) != 1) {
        fclose(f);
        return ESP_FAIL;
    }
    
    // 写入数据
    if (fwrite(data, 1, size, f) != size) {
        fclose(f);
        return ESP_FAIL; 
    }

    fclose(f);
    return ESP_OK;
}

// 开始事务
esp_err_t storage_transaction_begin(storage_context_t* ctx) {
    if (!ctx || !ctx->modules.transaction) {
        return ESP_ERR_INVALID_ARG;
    }

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);
    
    // 重置事务状态
    ctx->modules.transaction->in_progress = true;
    ctx->modules.transaction->header.status = TRANSACTION_STARTED;
    
    xSemaphoreGive(ctx->mutex);
    
    return ESP_OK;
}

// 提交事务
esp_err_t storage_transaction_commit(storage_context_t* ctx) {
    if (!ctx || !ctx->modules.transaction || 
        !ctx->modules.transaction->in_progress) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;
    char log_path[FILE_PATH_MAX];
    snprintf(log_path, sizeof(log_path), "%s%s", 
             ctx->config.base_path, TRANSACTION_PATH);

    xSemaphoreTake(ctx->mutex, portMAX_DELAY);

    do {
        // 更新事务状态
        ctx->modules.transaction->header.status = TRANSACTION_COMMITTED;
        
        // 写入更新后的头部
        FILE* f = fopen(log_path, "r+b");
        if (!f) {
            ret = ESP_FAIL;
            break;
        }
        
        if (fwrite(&ctx->modules.transaction->header, 
                   sizeof(transaction_header_t), 1, f) != 1) {
            fclose(f);
            ret = ESP_FAIL;
            break;
        }
        fclose(f);

        // 清除事务状态
        ctx->modules.transaction->in_progress = false;
        
    } while(0);
    
    xSemaphoreGive(ctx->mutex);
    return ret;
}

// 断电恢复
esp_err_t storage_power_fail_recover(storage_context_t* ctx) {
    if (!ctx) {
        return ESP_ERR_INVALID_ARG;
    }

    char log_path[FILE_PATH_MAX];
    snprintf(log_path, sizeof(log_path), "%s%s", 
             ctx->config.base_path, TRANSACTION_PATH);

    FILE* f = fopen(log_path, "rb");
    if (!f) {
        return ESP_OK; // 无需恢复
    }

    transaction_header_t header;
    if (fread(&header, sizeof(header), 1, f) != 1) {
        fclose(f);
        return ESP_FAIL;
    }

    if (header.magic != TRANSACTION_MAGIC) {
        fclose(f);
        return ESP_FAIL;
    }

    if (header.status == TRANSACTION_STARTED) {
        // 分配恢复缓冲区
        void* data = malloc(header.data_size);
        if (!data) {
            fclose(f);
            return ESP_ERR_NO_MEM;
        }

        // 读取事务数据
        if (fread(data, 1, header.data_size, f) != header.data_size) {
            free(data);
            fclose(f);
            return ESP_FAIL;
        }

        // 验证校验和
        uint32_t crc;
        esp_err_t ret = storage_calc_crc32(data, header.data_size, &crc);
        if (ret != ESP_OK || crc != header.checksum) {
            free(data);
            fclose(f);
            return ESP_FAIL;
        }

        // 恢复文件
        ret = ctx->interface->write(ctx, header.path, data, header.data_size);
        
        free(data);
        fclose(f);
        return ret;
    }

    fclose(f);
    return ESP_OK;
}
// components/perf/storage_perf.c
#include <string.h>
#include "esp_log.h"
#include "esp_timer.h"
#include "storage_perf.h"
#include "storage_types.h"

static const char *TAG = "storage_perf";

// 性能监控回调函数类型
typedef void (*perf_callback_t)(void* ctx, const char* metric, uint32_t value);

// 性能统计上下文
typedef struct {
    fs_perf_stats_t stats;
    struct {
        bool monitoring_enabled;
        bool collect_detailed;
        uint32_t sample_interval;
        perf_callback_t callback;
        void* callback_ctx;
    } config;
    SemaphoreHandle_t mutex;
} perf_context_t;

// 性能监控初始化
esp_err_t storage_perf_init(storage_context_t* ctx) {
    if (!ctx) {
        return ESP_ERR_INVALID_ARG;
    }

    perf_context_t* perf_ctx = calloc(1, sizeof(perf_context_t));
    if (!perf_ctx) {
        return ESP_ERR_NO_MEM;
    }

    perf_ctx->mutex = xSemaphoreCreateMutex();
    if (!perf_ctx->mutex) {
        free(perf_ctx);
        return ESP_ERR_NO_MEM;
    }

    // 初始化配置
    perf_ctx->config.monitoring_enabled = true;
    perf_ctx->config.collect_detailed = false;
    perf_ctx->config.sample_interval = 1000; // 1秒

    ctx->modules.perf_ctx = perf_ctx;
    
    ESP_LOGI(TAG, "Performance monitoring initialized");
    return ESP_OK;
}

// 性能监控清理
void storage_perf_deinit(storage_context_t* ctx) {
    if (!ctx || !ctx->modules.perf_ctx) {
        return;
    }

    perf_context_t* perf_ctx = (perf_context_t*)ctx->modules.perf_ctx;

    if (perf_ctx->mutex) {
        vSemaphoreDelete(perf_ctx->mutex);
    }

    free(perf_ctx);
    ctx->modules.perf_ctx = NULL;

    ESP_LOGI(TAG, "Performance monitoring deinitialized");
}

// 更新性能统计
void storage_perf_update_stats(storage_context_t* ctx, bool is_read, 
                             bool cache_hit, uint64_t op_time) {
    if (!ctx || !ctx->modules.perf_ctx) {
        return;
    }

    perf_context_t* perf_ctx = (perf_context_t*)ctx->modules.perf_ctx;

    xSemaphoreTake(perf_ctx->mutex, portMAX_DELAY);

    if (is_read) {
        if (cache_hit) {
            perf_ctx->stats.cache_hits++;
        } else {
            perf_ctx->stats.cache_misses++;
        }
        perf_ctx->stats.operations.read_ops++;
        perf_ctx->stats.total_read_time += op_time;
    } else {
        perf_ctx->stats.operations.write_ops++;
        perf_ctx->stats.total_write_time += op_time;
    }

    // 触发回调
    if (perf_ctx->config.callback) {
        if (is_read) {
            perf_ctx->config.callback(perf_ctx->config.callback_ctx,
                                    "read_time", op_time);
        } else {
            perf_ctx->config.callback(perf_ctx->config.callback_ctx,
                                    "write_time", op_time);
        }
    }

    xSemaphoreGive(perf_ctx->mutex);
}

// 重置性能统计
void storage_perf_reset_stats(storage_context_t* ctx) {
    if (!ctx || !ctx->modules.perf_ctx) {
        return;
    }

    perf_context_t* perf_ctx = (perf_context_t*)ctx->modules.perf_ctx;

    xSemaphoreTake(perf_ctx->mutex, portMAX_DELAY);
    memset(&perf_ctx->stats, 0, sizeof(perf_ctx->stats));
    xSemaphoreGive(perf_ctx->mutex);

    ESP_LOGI(TAG, "Performance statistics reset");
}

// 获取性能统计
esp_err_t storage_perf_get_stats(storage_context_t* ctx, fs_perf_stats_t* stats) {
    if (!ctx || !ctx->modules.perf_ctx || !stats) {
        return ESP_ERR_INVALID_ARG;
    }

    perf_context_t* perf_ctx = (perf_context_t*)ctx->modules.perf_ctx;

    xSemaphoreTake(perf_ctx->mutex, portMAX_DELAY);
    memcpy(stats, &perf_ctx->stats, sizeof(fs_perf_stats_t));
    xSemaphoreGive(perf_ctx->mutex);

    return ESP_OK;
}

// 设置性能监控配置
esp_err_t storage_perf_set_config(storage_context_t* ctx, 
                                const void* config) {
    if (!ctx || !ctx->modules.perf_ctx || !config) {
        return ESP_ERR_INVALID_ARG;
    }

    perf_context_t* perf_ctx = (perf_context_t*)ctx->modules.perf_ctx;
    const fs_perf_config_t* perf_config = (const fs_perf_config_t*)config;

    xSemaphoreTake(perf_ctx->mutex, portMAX_DELAY);
    perf_ctx->config.monitoring_enabled = perf_config->enable_monitoring;
    perf_ctx->config.collect_detailed = perf_config->collect_detailed_stats;
    perf_ctx->config.sample_interval = perf_config->sample_interval;
    xSemaphoreGive(perf_ctx->mutex);

    return ESP_OK;
}

// 注册性能回调
esp_err_t storage_perf_register_callback(storage_context_t* ctx,
                                       perf_callback_t callback,
                                       void* callback_ctx) {
    if (!ctx || !ctx->modules.perf_ctx || !callback) {
        return ESP_ERR_INVALID_ARG;
    }

    perf_context_t* perf_ctx = (perf_context_t*)ctx->modules.perf_ctx;

    xSemaphoreTake(perf_ctx->mutex, portMAX_DELAY);
    perf_ctx->config.callback = callback;
    perf_ctx->config.callback_ctx = callback_ctx;
    xSemaphoreGive(perf_ctx->mutex);

    return ESP_OK;
}

// 性能优化预取配置
esp_err_t storage_perf_enable_prefetch(storage_context_t* ctx, bool enable) {
    if (!ctx || !ctx->modules.cache_ctx) {
        return ESP_ERR_INVALID_ARG;
    }

    // 更新缓存预取设置
    return storage_cache_set_prefetch(ctx, enable);
}

// 执行性能优化
esp_err_t storage_perf_optimize(storage_context_t* ctx, 
                              const fs_perf_opt_config_t* config) {
    if (!ctx || !config) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;

    do {
        // 配置预取
        ret = storage_perf_enable_prefetch(ctx, config->enable_prefetch);
        if (ret != ESP_OK) break;

        // 配置缓存
        if (ctx->modules.cache_ctx) {
            ret = storage_cache_set_config(ctx, config);
            if (ret != ESP_OK) break;
        }

        // 配置DMA优化
        if (ctx->modules.dma_ctx) {
            ret = storage_dma_optimize(ctx, config->optimize_small_io ? 
                                     DMA_MODE_SCATTER : DMA_MODE_SINGLE);
            if (ret != ESP_OK) break;
        }

    } while(0);

    return ret;
}

// 计算性能指标
esp_err_t storage_perf_calculate_metrics(storage_context_t* ctx,
                                       uint32_t* read_iops,
                                       uint32_t* write_iops,
                                       float* cache_hit_ratio) {
    if (!ctx || !ctx->modules.perf_ctx || 
        !read_iops || !write_iops || !cache_hit_ratio) {
        return ESP_ERR_INVALID_ARG;
    }

    perf_context_t* perf_ctx = (perf_context_t*)ctx->modules.perf_ctx;

    xSemaphoreTake(perf_ctx->mutex, portMAX_DELAY);

    uint64_t total_time_ms = (perf_ctx->stats.total_read_time + 
                             perf_ctx->stats.total_write_time) / 1000;
    
    if (total_time_ms > 0) {
        *read_iops = (perf_ctx->stats.operations.read_ops * 1000) / 
                     total_time_ms;
        *write_iops = (perf_ctx->stats.operations.write_ops * 1000) / 
                      total_time_ms;
    } else {
        *read_iops = 0;
        *write_iops = 0;
    }

    uint32_t total_cache_ops = perf_ctx->stats.cache_hits + 
                              perf_ctx->stats.cache_misses;
    if (total_cache_ops > 0) {
        *cache_hit_ratio = (float)perf_ctx->stats.cache_hits / 
                          total_cache_ops;
    } else {
        *cache_hit_ratio = 0.0f;
    }

    xSemaphoreGive(perf_ctx->mutex);

    return ESP_OK;
}


// components/error/storage_error.c
#include <string.h>
#include "esp_log.h"
#include "storage_error.h"
#include "storage_types.h"

static const char *TAG = "storage_error";

// 错误处理初始化
esp_err_t storage_error_init(storage_context_t* ctx) {
    if (!ctx) {
        return ESP_ERR_INVALID_ARG;
    }

    // 分配错误上下文
    fs_error_ctx_t* error_ctx = calloc(1, sizeof(fs_error_ctx_t));
    if (!error_ctx) {
        return ESP_ERR_NO_MEM;
    }

    // 创建互斥锁
    error_ctx->mutex = xSemaphoreCreateMutex();
    if (!error_ctx->mutex) {
        free(error_ctx);
        return ESP_ERR_NO_MEM;
    }

    // 初始化错误配置
    error_ctx->config.auto_recover = true;
    error_ctx->config.retry_limit = 3;
    error_ctx->config.recover_timeout = 1000; // 1秒

    error_ctx->error_count = 0;
    error_ctx->error_index = 0;

    ctx->modules.error_ctx = error_ctx;
    
    ESP_LOGI(TAG, "Error handling initialized");
    return ESP_OK;
}

// 错误处理清理
void storage_error_deinit(storage_context_t* ctx) {
    if (!ctx || !ctx->modules.error_ctx) {
        return;
    }

    fs_error_ctx_t* error_ctx = (fs_error_ctx_t*)ctx->modules.error_ctx;

    if (error_ctx->mutex) {
        vSemaphoreDelete(error_ctx->mutex);
    }

    free(error_ctx);
    ctx->modules.error_ctx = NULL;

    ESP_LOGI(TAG, "Error handling deinitialized");
}

// 记录错误
void storage_error_record(storage_context_t* ctx, fs_error_type_t type,
                         uint32_t code, const char* location) {
    if (!ctx || !ctx->modules.error_ctx) {
        return;
    }

    fs_error_ctx_t* error_ctx = (fs_error_ctx_t*)ctx->modules.error_ctx;

    xSemaphoreTake(error_ctx->mutex, portMAX_DELAY);

    // 记录错误信息
    size_t index = error_ctx->error_index % 16;
    fs_error_info_t* error = &error_ctx->errors[index];

    error->type = type;
    error->code = code;
    error->timestamp = time(NULL);
    error->retry_count = 0;
    
    if (location) {
        strncpy(error->location, location, sizeof(error->location) - 1);
        error->location[sizeof(error->location) - 1] = '\0';
    } else {
        error->location[0] = '\0';
    }

    // 更新错误计数和索引
    error_ctx->error_count++;
    error_ctx->error_index = (error_ctx->error_index + 1) % 16;

    xSemaphoreGive(error_ctx->mutex);

    ESP_LOGE(TAG, "Error recorded: type=%d, code=%d, location=%s", 
             type, code, location ? location : "unknown");

    // 自动恢复
    if (error_ctx->config.auto_recover) {
        storage_error_recover(ctx, type);
    }
}

// 错误恢复
esp_err_t storage_error_recover(storage_context_t* ctx, fs_error_type_t type) {
    if (!ctx || !ctx->modules.error_ctx) {
        return ESP_ERR_INVALID_ARG;
    }

    fs_error_ctx_t* error_ctx = (fs_error_ctx_t*)ctx->modules.error_ctx;
    esp_err_t ret = ESP_OK;

    xSemaphoreTake(error_ctx->mutex, portMAX_DELAY);

    do {
        // 查找最近的相关错误
        fs_error_info_t* error = NULL;
        for (int i = 0; i < 16; i++) {
            size_t idx = (error_ctx->error_index - 1 - i) % 16;
            if (error_ctx->errors[idx].type == type) {
                error = &error_ctx->errors[idx];
                break;
            }
        }

        if (!error) {
            ret = ESP_ERR_NOT_FOUND;
            break;
        }

        // 检查重试次数
        if (error->retry_count >= error_ctx->config.retry_limit) {
            ret = ESP_ERR_INVALID_STATE;
            break;
        }

        // 根据错误类型执行恢复
        switch (type) {
            case FS_ERROR_DEVICE_FAIL:
                // 重新初始化设备
                if (ctx->device && ctx->device->init) {
                    ret = ctx->device->init(&ctx->config);
                }
                break;

            case FS_ERROR_FS_CORRUPT:
                // 尝试格式化
                if (ctx->interface && ctx->interface->format) {
                    ret = ctx->interface->format(ctx);
                }
                break;

            case FS_ERROR_DMA_FAIL:
                // 重新初始化DMA
                if (ctx->modules.dma_ctx) {
                    storage_dma_deinit(ctx);
                    ret = storage_dma_init(ctx);
                }
                break;

            case FS_ERROR_CACHE_FAIL:
                // 重置缓存
                if (ctx->modules.cache_ctx) {
                    storage_cache_clear(ctx);
                    ret = ESP_OK;
                }
                break;

            case FS_ERROR_PROTECTION:
                // 恢复数据保护
                if (ctx->modules.protect_ctx) {
                    ret = storage_protection_recover(ctx);
                }
                break;

            default:
                ret = ESP_ERR_NOT_SUPPORTED;
                break;
        }

        // 更新重试计数
        if (ret == ESP_OK) {
            error->retry_count++;
        }

    } while(0);

    xSemaphoreGive(error_ctx->mutex);

    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Error recovery failed: type=%d, err=%d", type, ret);
    } else {
        ESP_LOGI(TAG, "Error recovered: type=%d", type);
    }

    return ret;
}

// 获取最近错误
esp_err_t storage_error_get_last(storage_context_t* ctx, fs_error_info_t* error) {
    if (!ctx || !ctx->modules.error_ctx || !error) {
        return ESP_ERR_INVALID_ARG;
    }

    fs_error_ctx_t* error_ctx = (fs_error_ctx_t*)ctx->modules.error_ctx;
    
    xSemaphoreTake(error_ctx->mutex, portMAX_DELAY);

    if (error_ctx->error_count > 0) {
        size_t last_idx = (error_ctx->error_index - 1) % 16;
        memcpy(error, &error_ctx->errors[last_idx], sizeof(fs_error_info_t));
        xSemaphoreGive(error_ctx->mutex);
        return ESP_OK;
    }

    xSemaphoreGive(error_ctx->mutex);
    return ESP_ERR_NOT_FOUND;
}

// 清除错误记录
void storage_error_clear(storage_context_t* ctx) {
    if (!ctx || !ctx->modules.error_ctx) {
        return;
    }

    fs_error_ctx_t* error_ctx = (fs_error_ctx_t*)ctx->modules.error_ctx;

    xSemaphoreTake(error_ctx->mutex, portMAX_DELAY);
    
    memset(error_ctx->errors, 0, sizeof(error_ctx->errors));
    error_ctx->error_count = 0;
    error_ctx->error_index = 0;
    
    xSemaphoreGive(error_ctx->mutex);

    ESP_LOGI(TAG, "Error records cleared");
}

// components/async/storage_async.c
#include <string.h>
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "storage_async.h"
#include "storage_types.h"

static const char *TAG = "storage_async";

// 异步操作队列结构
typedef struct {
    QueueHandle_t op_queue;           // 操作队列
    SemaphoreHandle_t queue_mutex;    // 队列互斥锁
    TaskHandle_t worker_task;         // 工作线程
    bool queue_paused;                // 队列暂停标志
    uint32_t active_ops;              // 活动操作计数
} async_queue_t;

// 工作线程函数声明
static void async_worker_task(void* arg);

// 异步管理器初始化
esp_err_t storage_async_init(storage_context_t* ctx) {
    if (!ctx) {
        return ESP_ERR_INVALID_ARG;
    }

    // 分配异步上下文
    async_queue_t* async_ctx = calloc(1, sizeof(async_queue_t));
    if (!async_ctx) {
        return ESP_ERR_NO_MEM;
    }

    // 创建操作队列
    async_ctx->op_queue = xQueueCreate(MAX_ASYNC_OPERATIONS, 
                                     sizeof(async_operation_t*));
    if (!async_ctx->op_queue) {
        free(async_ctx);
        return ESP_ERR_NO_MEM;
    }

    // 创建互斥锁
    async_ctx->queue_mutex = xSemaphoreCreateMutex();
    if (!async_ctx->queue_mutex) {
        vQueueDelete(async_ctx->op_queue);
        free(async_ctx);
        return ESP_ERR_NO_MEM;
    }

    // 创建工作线程
    BaseType_t ret = xTaskCreate(async_worker_task, "async_worker",
                                ASYNC_TASK_STACK_SIZE, ctx,
                                ASYNC_TASK_PRIORITY,
                                &async_ctx->worker_task);
    if (ret != pdPASS) {
        vQueueDelete(async_ctx->op_queue);
        vSemaphoreDelete(async_ctx->queue_mutex);
        free(async_ctx);
        return ESP_ERR_NO_MEM;
    }

    ctx->modules.async_ctx = async_ctx;
    
    ESP_LOGI(TAG, "Async operations initialized");
    return ESP_OK;
}

// 异步管理器清理
void storage_async_deinit(storage_context_t* ctx) {
    if (!ctx || !ctx->modules.async_ctx) {
        return;
    }

    async_queue_t* async_ctx = (async_queue_t*)ctx->modules.async_ctx;

    // 等待所有操作完成
    while (async_ctx->active_ops > 0) {
        vTaskDelay(pdMS_TO_TICKS(10));
    }

    // 删除工作线程
    if (async_ctx->worker_task) {
        vTaskDelete(async_ctx->worker_task);
    }

    // 清理队列中的剩余操作
    async_operation_t* op;
    while (xQueueReceive(async_ctx->op_queue, &op, 0) == pdTRUE) {
        if (op->buffer) {
            free(op->buffer);
        }
        if (op->path) {
            free(op->path);
        }
        free(op);
    }

    vQueueDelete(async_ctx->op_queue);
    vSemaphoreDelete(async_ctx->queue_mutex);
    free(async_ctx);
    ctx->modules.async_ctx = NULL;

    ESP_LOGI(TAG, "Async operations deinitialized");
}

// 工作线程实现
static void async_worker_task(void* arg) {
    storage_context_t* ctx = (storage_context_t*)arg;
    async_queue_t* async_ctx = (async_queue_t*)ctx->modules.async_ctx;
    async_operation_t* op;

    while (1) {
        // 等待操作
        if (xQueueReceive(async_ctx->op_queue, &op, portMAX_DELAY) == pdTRUE) {
            esp_err_t ret = ESP_OK;

            // 检查队列是否暂停
            if (async_ctx->queue_paused) {
                continue;
            }

            async_ctx->active_ops++;

            // 执行操作
            switch (op->type) {
                case ASYNC_OP_READ:
                    {
                        size_t read_size;
                        ret = ctx->interface->read(ctx, op->path, op->buffer,
                                                 op->size, &read_size);
                    }
                    break;

                case ASYNC_OP_WRITE:
                    ret = ctx->interface->write(ctx, op->path, op->buffer,
                                              op->size);
                    break;

                case ASYNC_OP_DELETE:
                    ret = ctx->interface->remove(ctx, op->path);
                    break;

                case ASYNC_OP_RENAME:
                    // 重命名操作需要额外的路径参数
                    ret = ctx->interface->rename(ctx, op->path,
                                               op->context);
                    break;

                default:
                    ret = ESP_ERR_NOT_SUPPORTED;
                    break;
            }

            // 更新操作状态
            op->state = (ret == ESP_OK) ? ASYNC_STATE_COMPLETED : 
                                        ASYNC_STATE_ERROR;

            // 调用回调
            if (op->callback) {
                op->callback(op->context, ret);
            }

            // 自动重试
            if (ret != ESP_OK && op->config.auto_retry) {
                if (op->config.retry_count < 3) {
                    op->config.retry_count++;
                    op->state = ASYNC_STATE_QUEUED;
                    xQueueSendToBack(async_ctx->op_queue, &op, 0);
                    async_ctx->active_ops--;
                    continue;
                }
            }

            // 清理操作资源
            if (op->buffer) {
                free(op->buffer);
            }
            if (op->path) {
                free(op->path);
            }
            free(op);

            async_ctx->active_ops--;
        }
    }
}

// 异步读取实现
esp_err_t storage_async_read(storage_context_t* ctx, const char* path,
                            void* data, size_t size,
                            async_callback_t callback, void* user_ctx) {
    if (!ctx || !ctx->modules.async_ctx || !path || !data) {
        return ESP_ERR_INVALID_ARG;
    }

    async_queue_t* async_ctx = (async_queue_t*)ctx->modules.async_ctx;

    // 创建异步操作
    async_operation_t* op = calloc(1, sizeof(async_operation_t));
    if (!op) {
        return ESP_ERR_NO_MEM;
    }

    op->type = ASYNC_OP_READ;
    op->path = strdup(path);
    op->buffer = data;
    op->size = size;
    op->callback = callback;
    op->context = user_ctx;
    op->state = ASYNC_STATE_QUEUED;

    // 默认配置
    op->config.priority = ASYNC_TASK_PRIORITY;
    op->config.timeout = portMAX_DELAY;
    op->config.auto_retry = true;
    op->config.retry_count = 0;

    // 加入队列
    if (xQueueSend(async_ctx->op_queue, &op, 0) != pdTRUE) {
        free(op->path);
        free(op);
        return ESP_ERR_NO_MEM;
    }

    return ESP_OK;
}

// 异步写入实现
esp_err_t storage_async_write(storage_context_t* ctx, const char* path,
                             const void* data, size_t size,
                             async_callback_t callback, void* user_ctx) {
    if (!ctx || !ctx->modules.async_ctx || !path || 
        (!data && size > 0)) {
        return ESP_ERR_INVALID_ARG;
    }

    async_queue_t* async_ctx = (async_queue_t*)ctx->modules.async_ctx;

    // 创建异步操作
    async_operation_t* op = calloc(1, sizeof(async_operation_t));
    if (!op) {
        return ESP_ERR_NO_MEM;
    }

    op->type = ASYNC_OP_WRITE;
    op->path = strdup(path);
    op->size = size;
    op->callback = callback;
    op->context = user_ctx;
    op->state = ASYNC_STATE_QUEUED;

    // 复制数据
    if (size > 0) {
        op->buffer = malloc(size);
        if (!op->buffer) {
            free(op->path);
            free(op);
            return ESP_ERR_NO_MEM;
        }
        memcpy(op->buffer, data, size);
    }

    // 默认配置
    op->config.priority = ASYNC_TASK_PRIORITY;
    op->config.timeout = portMAX_DELAY;
    op->config.auto_retry = true;
    op->config.retry_count = 0;

    // 加入队列
    if (xQueueSend(async_ctx->op_queue, &op, 0) != pdTRUE) {
        free(op->buffer);
        free(op->path);
        free(op);
        return ESP_ERR_NO_MEM;
    }

    return ESP_OK;
}

// 取消异步操作
esp_err_t storage_async_cancel(storage_context_t* ctx, const char* path) {
    if (!ctx || !ctx->modules.async_ctx || !path) {
        return ESP_ERR_INVALID_ARG;
    }

    async_queue_t* async_ctx = (async_queue_t*)ctx->modules.async_ctx;
    esp_err_t ret = ESP_ERR_NOT_FOUND;

    xSemaphoreTake(async_ctx->queue_mutex, portMAX_DELAY);

    // 遍历队列查找操作
    UBaseType_t count = uxQueueMessagesWaiting(async_ctx->op_queue);
    for (UBaseType_t i = 0; i < count; i++) {
        async_operation_t* op;
        if (xQueueReceive(async_ctx->op_queue, &op, 0) == pdTRUE) {
            if (strcmp(op->path, path) == 0 && 
                op->state == ASYNC_STATE_QUEUED) {
                // 找到目标操作，释放资源
                if (op->buffer) {
                    free(op->buffer);
                }
                free(op->path);
                free(op);
                ret = ESP_OK;
            } else {
                // 其他操作重新入队
                xQueueSendToBack(async_ctx->op_queue, &op, 0);
            }
        }
    }

    xSemaphoreGive(async_ctx->queue_mutex);
    return ret;
}

// 等待异步操作完成
esp_err_t storage_async_wait(storage_context_t* ctx, const char* path,
                            TickType_t timeout) {
    if (!ctx || !ctx->modules.async_ctx || !path) {
        return ESP_ERR_INVALID_ARG;
    }

    async_queue_t* async_ctx = (async_queue_t*)ctx->modules.async_ctx;
    TickType_t start_tick = xTaskGetTickCount();

    while (xTaskGetTickCount() - start_tick < timeout) {
        UBaseType_t count = uxQueueMessagesWaiting(async_ctx->op_queue);
        bool found = false;

        xSemaphoreTake(async_ctx->queue_mutex, portMAX_DELAY);

        for (UBaseType_t i = 0; i < count; i++) {
            async_operation_t* op;
            if (xQueueReceive(async_ctx->op_queue, &op, 0) == pdTRUE) {
                if (strcmp(op->path, path) == 0) {
                    found = true;
                }
                xQueueSendToBack(async_ctx->op_queue, &op, 0);
            }
        }

        xSemaphoreGive(async_ctx->queue_mutex);

        if (!found) {
            return ESP_OK;
        }

        vTaskDelay(pdMS_TO_TICKS(10));
    }

    return ESP_ERR_TIMEOUT;
}

// 获取异步操作状态
async_state_t storage_async_get_state(storage_context_t* ctx, const char* path) {
    if (!ctx || !ctx->modules.async_ctx || !path) {
        return ASYNC_STATE_ERROR;
    }

    async_queue_t* async_ctx = (async_queue_t*)ctx->modules.async_ctx;
    async_state_t state = ASYNC_STATE_IDLE;

    xSemaphoreTake(async_ctx->queue_mutex, portMAX_DELAY);

    // 查找操作状态
    UBaseType_t count = uxQueueMessagesWaiting(async_ctx->op_queue);
    for (UBaseType_t i = 0; i < count; i++) {
        async_operation_t* op;
        if (xQueueReceive(async_ctx->op_queue, &op, 0) == pdTRUE) {
            if (strcmp(op->path, path) == 0) {
                state = op->state;
            }
            xQueueSendToBack(async_ctx->op_queue, &op, 0);
        }
    }

    xSemaphoreGive(async_ctx->queue_mutex);
    return state;
}